package cn.znzz.cjm.basic.service.impl;

import cn.znzz.cjm.basic.constant.LoginConstant;
import cn.znzz.cjm.basic.dto.LoginDto;
import cn.znzz.cjm.basic.exception.BusinessException;
import cn.znzz.cjm.basic.service.ILoginService;
import cn.znzz.cjm.basic.util.AjaxResult;
import cn.znzz.cjm.basic.util.HttpClientUtils;
import cn.znzz.cjm.basic.util.MD5Utils;
import cn.znzz.cjm.basic.util.StrUtils;
import cn.znzz.cjm.user.domain.Logininfo;
import cn.znzz.cjm.user.domain.User;
import cn.znzz.cjm.user.domain.WxUser;
import cn.znzz.cjm.user.mapper.LogininfoMapper;
import cn.znzz.cjm.user.mapper.UserMapper;
import cn.znzz.cjm.user.mapper.WxUserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String ,Object> account(LoginDto dto) {

        //1.空校验
        if(StringUtils.isEmpty(dto.getUsername())
                || StringUtils.isEmpty(dto.getPassword())
                || StringUtils.isEmpty(dto.getType())){
            throw new BusinessException("请填写完整信息");
        }
        //2.根据username+type查询logininfo用户是否存在
        Logininfo logininfo=logininfoMapper.loadByDto(dto);
        //3.不存在就报错
        if(logininfo==null){
            throw new BusinessException("账号或者密码错误");
        }
        //4.再判断密码是否一致
        String salt = logininfo.getSalt();
        //登录的密码加密
        String md5Password = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if(!md5Password.equalsIgnoreCase(logininfo.getPassword())) {
            //5.密码不一致报错
            throw new BusinessException("用户名或者密码错误");
        }
        //6.密码一致，登录成功

        //7.存储redis，生成token随机码，设置三十分钟过期
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//登录成功的人的对象
                30,
                TimeUnit.MINUTES//设置三十分钟过期
        );
        //8.返回前端数据 token，logininfo信息
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);

        //吧颜值和密码置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }

    @Override
    public AjaxResult wechat(Map<String, String> param) {
        String code = param.get("code");
        if(!StringUtils.hasLength(code)){
            throw new BusinessException("没有得到你的码！");
        }
        //拿到授权码
        String getTokenUrl= LoginConstant.WXUSER_GET_TOKEN_URL.replace("APPID",LoginConstant.APPID)
                .replace("SECRET",LoginConstant.SECRET)
                .replace("CODE",code);

        String tokenObjStr = HttpClientUtils.httpGet(getTokenUrl);
        System.out.println(tokenObjStr);
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        Object accessToken = jsonObject.get("access_token");
        String openId = jsonObject.getString("openid");


        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        if(wxUser!=null && wxUser.getUser_id()!=null){
            Logininfo logininfo=logininfoMapper.loadByUserId(wxUser.getUser_id());
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,//登录成功的人的对象
                    30,
                    TimeUnit.MINUTES//设置三十分钟过期
            );
            //8.返回前端数据 token，logininfo信息
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);

            //吧颜值和密码置空
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);

            return AjaxResult.me().setResultObj(map);
        }
        //第一次扫码，绑定
        else {
            String binderUrlParams = "accessToken=" + accessToken + "&openId=" + openId;
            return AjaxResult.me().setSuccess(false).setResultObj(binderUrlParams);
        }
    }

    @Override
    public Map<String, Object> binder(Map<String, String> param) {
        String phone = param.get("phone");
        String verifyCode = param.get("verifyCode");
        String accessToken = param.get("accessToken");
        String openId = param.get("openId");

        if(!StringUtils.hasLength(phone)
                ||!StringUtils.hasLength(verifyCode)
                ||!StringUtils.hasLength(accessToken)
                ||!StringUtils.hasLength(openId)){
            throw new BusinessException("参数有问题");
        }
        //4.验证码是否失效 从redis中拿
        Object codeTmp = redisTemplate.opsForValue().get(LoginConstant.PHONE_BINDER + phone);
        //5.没拿到验证码，验证码过期，重新发送
        if(codeTmp == null){
            throw new BusinessException("验证码失效，请重新获取");
        }
        //6.拿到了验证码，判断是否一致，不用区分大小写
        if(!verifyCode.equalsIgnoreCase(codeTmp.toString().split(":")[0])){
            throw new BusinessException("验证码错误");
        }

        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo=null;
        if(user!=null){
            logininfo=logininfoMapper.loadById(user.getLogininfo_id());
        }else{
            user=initUser(phone);
            logininfo=user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }

        String getWxUserUrl= LoginConstant.WXUSER_GET_URL.replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);

        String wxUserStr = HttpClientUtils.httpGet(getWxUserUrl);
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        wxUser.setUser_id(user.getId());
        wxUserMapper.save(wxUser);


        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//登录成功的人的对象
                30,
                TimeUnit.MINUTES//设置三十分钟过期
        );
        //8.返回前端数据 token，logininfo信息
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);

        //吧颜值和密码置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);

        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//一定要设置
        return logininfo;
    }

    private User initUser(String phone) {
        User user=new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //生成颜值
        String salt = StrUtils.getComplexRandomString(32);
        //加密密码
        String md5Password = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(md5Password);

        return user;
    }
}










